﻿using System;
using System.Linq;
using Csla;
using BizControl.Library.BusinessObjects.Models;
using BizControl.Library.Criterias;
using Csla.Data;
using BizControl.Library.Security;
using BizControl.Resources;
using BizControl.DalLinq;

namespace BizControl.Library.BusinessObjects.BusinessRoles
{
  [Serializable()]
  public class BusinessRoleInfoList : ReadOnlyListBase<BusinessRoleInfoList, BusinessRoleInfo>
  {
    public BusinessRoleInfo this[Guid roleIdSearchFor]
    {
      get
      {
        foreach (BusinessRoleInfo role in this)
        {
          if (role.Id == roleIdSearchFor)
            return role;
        }
        return null;
      }
    }

    public BusinessRoleInfo this[BusinessRoleInfo roleSearchFor]
    {
      get
      {
        foreach (BusinessRoleInfo role in this)
        {
          if (role.Id == roleSearchFor.Id)
            return role;
        }
        return null;
      }
    }

    #region  Factory Methods

    public static BusinessRoleInfoList GetBusinessRoleInfoList(ModelBO model, bool includeEmptyRole = false)
    {
      return DataPortal.Fetch<BusinessRoleInfoList>(new ModelAndBoolCriteria(model, includeEmptyRole));
    }

    public static BusinessRoleInfoList GetBusinessRoleInfoList(bool includeEmptyRole = false)
    {
      var model = SecurityChecks.GetCurrentModel();
      return DataPortal.Fetch<BusinessRoleInfoList>(new ModelAndBoolCriteria(model, includeEmptyRole));
    }

    #endregion

    #region  Data Access

    private void DataPortal_Fetch(ModelAndBoolCriteria criteria)
    {
      Fetch(criteria);
    }

    private void Fetch(ModelAndBoolCriteria criteria)
    {
      if (null == criteria.Model) throw new ArgumentNullException(ExceptionsMessages.ModelNullReference);
      RaiseListChangedEvents = false;
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var data = from r in ctx.DataContext.BusinessRoles
                   where !r.IsDeleted && r.Model == criteria.Model.ModelId
                   select new BusinessRoleInfo(r);
        this.AddRange(data);
      }
      if (criteria.IncludeEmptyObject)
        this.Add(new BusinessRoleInfo(BusinessRoleBO.GetEmptyRole()));
      RaiseListChangedEvents = true;
    }

    #endregion

  }

}
